package top.ijiujiu.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.ijiujiu.config.WeChatProperties;
import top.ijiujiu.util.AppUtil;
import top.ijiujiu.util.SHA1Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Wx
 *
 * @Author 神秘的黄瓜
 * @Version 1.0
 * @Date 2020-04-10
 */
@Controller
@RequestMapping("weixin")
public class Wx {

    private final static Logger LOGGER = LoggerFactory.getLogger(Wx.class);


    private static final String TOKEN = "pengxl";

    @Autowired
    private WeChatProperties properties;

    /**
     * 拼接跳转地址，用于获取openid
     *
     * @param targetUrl
     * @return
     */
    public String getRedirectUrl(String targetUrl) throws UnsupportedEncodingException {
        String url = Base64.encodeBase64URLSafeString(targetUrl.getBytes()).replaceAll("\\+", "-").replaceAll("/", "_");
        return properties.getWeChatUrl().replaceAll("APPID", properties.getAppId()).replaceAll("REDIRECT_URI", URLEncoder.encode(url, "UTF-8")).replaceAll("STATE", "1");
    }


    /**
     * 入口
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "login")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        try {
            String serverUrl = AppUtil.getBaseUrl(request);
            String redirectUrl = Base64.encodeBase64URLSafeString((serverUrl + "weixin/code").getBytes()).replaceAll("\\+", "-").replaceAll("/", "_");
            response.sendRedirect(getRedirectUrl(serverUrl + "weixin/code/" + redirectUrl));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 入口
     *
     * @param request
     * @param response
     * @param data
     */
    @RequestMapping(value = "code/{redirectUrl}")
    public void code(HttpServletRequest request, HttpServletResponse response, @PathVariable("redirectUrl") String redirectUrl, String code, String state) {
        try {
            String serverUrl = AppUtil.getBaseUrl(request);
            LOGGER.info(serverUrl);
            response.sendRedirect(getRedirectUrl(serverUrl + "sysBuriedLog/getOpenId"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("getOpenId")
    public String getOpenId(String openId) {
        return org.springframework.util.StringUtils.isEmpty(openId) ? "" : openId;
    }


    @GetMapping("verify")
    @ResponseBody
    public String verify(String signature, String timestamp, String nonce, String echostr){
        List<String> list=new ArrayList<>();
        list.add(nonce);
        list.add(timestamp);
        list.add(TOKEN);
        //字典序排序
        Collections.sort(list);
        String encode = SHA1Util.encode(StringUtils.join(list, ""));
        if(encode.equals(signature)){
            return echostr;
        }
        return null;

    }

}
